package com.example.leave.api.advice;

import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * @author lxh
 * @date 2020/11/26 下午4:17
 **/
@RestControllerAdvice
public class ExceptionControllerAdvice {
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String, String> handleBindException(BindException e) {
        FieldError error = e.getFieldError();
        Map<String, String> result = new HashMap<>(1);
        result.put(error.getField(), error.getDefaultMessage());
        return result;
    }

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String, String> handleIllegalArgumentException(IllegalArgumentException e) {
        Map<String, String> result = new HashMap<>(1);
        result.put("msg", e.getMessage());
        return result;
    }
}
